﻿using System;
using System.IO;
using System.Text;

namespace GLog
{
    public class BufferedTextFileLog : Log
    {
        public StringBuilder Buffer { get; set; }
        public string LogFileName { get; set; }
        public BufferedTextFileLog(string logFileName, ILog postLog = null, LogLevel displayLevel = LogLevel.Error|LogLevel.Message|LogLevel.Warning)
            : base(postLog, displayLevel: displayLevel)
        {
            if (string.IsNullOrWhiteSpace(logFileName))
            {
                throw new ArgumentNullException("logFileName is required.");
            }
            LogFileName = logFileName;

            Initial();
        }

        public override void Initial()
        {
            Buffer = new StringBuilder();
        }

        public override void WriteLog()
        {
            if (File.Exists(LogFileName))
            {
                File.Delete(LogFileName);
            }
            using (StreamWriter sw = new StreamWriter(LogFileName))
            {
                sw.Write(Buffer.ToString());
                Buffer = new StringBuilder();
            }
        }

        internal override void LogMessage(string info, LogLevel level)
        {
            if (Buffer == null)
            {
                throw new InvalidOperationException("Log is not initialized.");
            }
            Buffer.AppendFormat("{0}: {1}", level.ToString(), info);
            Buffer.AppendLine();
        }

        protected override void OutputHeader(string message)
        {
            Buffer.AppendLine("==========================================================================");
            Buffer.AppendLine(message);
            Buffer.AppendLine("==========================================================================");
        }
    }
}
